/*
 * @Author: 杨上漂
 * @Date: 2024-10-13 12:01:53
 * @LastEditors: 杨上漂
 * @LastEditTime: 2024-10-16 18:37:30
 * @FilePath: \gwlc\assets\scripts\gameMgr.ts
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
import { _decorator, Button, Color, Component, director, dragonBones, find, instantiate, JsonAsset, Label, macro, Node, Prefab, resources, RigidBody, RigidBody2D, sp, Sprite, SpriteFrame, sys, Tween, tween, UITransform, v2, v3 } from 'cc';
import { Player } from './Player';
import { Dictionary } from '../utils/Dictionary';
import { UserInfo } from '../startScene/UserInfo';
import { enemyTypeEnum, rewardEnum } from '../Enum';
import { EnemyMgr } from './EnemyMgr';
import { convertNumber, getDistance, getStartTime, randomNum, trackTarget } from '../utils/utils';
import { RewardCellItem } from './RewardCellItem';
import { StartSceneGameMgr } from '../startScene/StartSceneGameMgr';
import { Adsdk } from '../Adsdk';
import { Enemy } from './Enemy';
import { AudioMgr } from '../utils/AudioMgr';
import { TimeCountTable } from '../TimeCountTable';
import { SelectSkillPanel } from './SelectSkillPanel';
import { PoolMgr } from '../PoolMgr';
const { ccclass, property } = _decorator;

@ccclass('gameMgr')
export class gameMgr extends Component {

    @property(JsonAsset)
    skillCongfi: JsonAsset;

    @property(Prefab)
    minTipPre: Prefab;
    @property(Prefab)
    giftPre: Prefab;
    @property(Prefab)
    AngelPre: Prefab;
    @property(Prefab)
    rewardCellPre: Prefab;
    @property(Prefab)
    windEndSkillPropPre: Prefab;
    @property(Prefab)
    tornadoEndSkillPropPre: Prefab;
    @property(Prefab)
    rabidEndSkillPropPre: Prefab;
    @property(Prefab)
    widowTipPre: Prefab;
    beatCountTable: Node;
    LevelCountTable: Node;
    skillCellContent: Node;
    failPanel: Node;
    winPanel: Node;
    pausePanel: Node;
    giftPanel: Node
    windowPopTipRoot: Node
    enemyRoot: Node;
    buttleRoot: Node;
    roundRoot: Node;
    currSelectPetSp: Node;
    playerDieTimeCountDownNode: Node;
    endSkillPropRoot: Node;
    unLockEnemyTypeRoot: Node;
    isTornadoIng = false;

    static ins: gameMgr;

    isOpenZombieTide = false;
    unlockEnemyTypeArr = [];//已经解锁的敌人类型数组

    // giftTempUpdateTimeCount = 0;
    skillCongfiDic: Dictionary<number, any> = new Dictionary();

    tempPos = v2();
    tempCount = 0;
    isGamePause = false;
    playerSkillTypeTotalMun = 7//玩家技能种类总数
    private isPlayerDieTimeDowning = false;//是否处于死亡倒计时

    _windowWidth;
    _windowHeight;
    screenCellHeight;

    attackEnemyList = []

    get IsPlayerDieTimeDowning() {
        return this.isPlayerDieTimeDowning
    }
    set IsPlayerDieTimeDowning(value) {
        this.isPlayerDieTimeDowning = value;
        if (value == true) {
            this.playerDieTimeCountDownNode.active = true;
            tween(this.playerDieTimeCountDownNode.getChildByName("cell"))
                .to(0.5, { scale: v3(1.1, 1.1, 1) })
                .to(0.5, { scale: v3(1, 1, 1) })
                .union()
                .repeatForever()
                .start()
        }
        else {
            this.playerDieTimeCountDownNode.active = false;
            Tween.stopAllByTarget(this.playerDieTimeCountDownNode.getChildByName("cell"))
        }
    }
    tempUpdatePlayerDieTimeDown = 0;
    set TempUpdatePlayerDieTimeDown(value) {
        this.tempUpdatePlayerDieTimeDown = value;
        this.playerDieTimeCountDownNode.getChildByName("cell").getChildByName("Label").getComponent(Label).string = Math.round(this.playerDieTimeDownTotalMun - value) + ""
    }
    get TempUpdatePlayerDieTimeDown() {
        return this.tempUpdatePlayerDieTimeDown;
    }

    playerDieTimeDownTotalMun = 10;

    protected onLoad(): void {
        // let sysInfo ;

        // if (sys.platform == sys.Platform.WECHAT_GAME) {
        //     sysInfo = wx.getSystemInfoSync();
        //     this._windowWidth= sysInfo.windowWidth
        //     this._windowHeight= sysInfo.windowHeight
        // }
        // else if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
        //     // sysInfo = .getSystemInfoSync();
        //     this._windowWidth= sysInfo.windowWidth
        //     this._windowHeight= sysInfo.windowHeight
        // }
        // else{
        //     console.log("不是微信抖音环境")
        //     this._windowWidth=screen.width;
        //     this._windowHeight=screen.height;
        // }


        // this.screenCellHeight=this._windowHeight/100
        // console.log(this._windowWidth,this._windowHeight,"长宽")


        this.beatCountTable = find("Canvas/UI/topInfo/beatCountTable");
        this.LevelCountTable = find("Canvas/UI/topInfo/LevelCountTable");
        this.skillCellContent = find("Canvas/UI/skillCellPanel/content")
        this.failPanel = find("Canvas/UI/popRoot/failPanel")
        this.giftPanel = find("Canvas/UI/popRoot/giftPanel")
        this.windowPopTipRoot = find("Canvas/UI/windowPopTipRoot")
        this.enemyRoot = find("Canvas/bg/enemyRoot");
        this.buttleRoot = find("Canvas/bg/buttleRoot");
        this.roundRoot = find("Canvas/bg/roundRoot");
        this.pausePanel = find("Canvas/UI/popRoot/pausePanel")
        this.winPanel = find("Canvas/UI/popRoot/winPanel")
        this.playerDieTimeCountDownNode = find("Canvas/UI/playerDieTimeCountDown")
        this.endSkillPropRoot = find("Canvas/UI/endSkillRoot/endSkillPropRoot")
        this.currSelectPetSp = find("Canvas/bg/playerRoot/petRoot/petSp");
        this.unLockEnemyTypeRoot = find("Canvas/UI/unLockEnemyTypeRoot");
    }

    protected start(): void {
        gameMgr.ins = this;

        //获取配置
        this.skillCongfi.json.forEach(element => {
            this.skillCongfiDic.set(element.playerSkillType, element);
        });

        if (AudioMgr.ins.isAudioBgm) {
            AudioMgr.ins.play("audio/bgm1");
            resources.load("UIImg/audioOpen/spriteFrame", SpriteFrame, (err, res) => {
                this.pausePanel.getChildByName("audioBgmToggleImg").getComponent(Sprite).spriteFrame = res;
            })
        }
        else {
            AudioMgr.ins.stop();
            resources.load("UIImg/audioClose/spriteFrame", SpriteFrame, (err, res) => {
                this.pausePanel.getChildByName("audioBgmToggleImg").getComponent(Sprite).spriteFrame = res;
            })
        }

        if (AudioMgr.ins.isAudioEffect) {
            resources.load("UIImg/audioClose/spriteFrame", SpriteFrame, (err, res) => {
                this.pausePanel.getChildByName("audioEffectToggleImg").getComponent(Sprite).spriteFrame = res;
            })
        }
        else {
            resources.load("UIImg/audioClose/spriteFrame", SpriteFrame, (err, res) => {
                this.pausePanel.getChildByName("audioEffectToggleImg").getComponent(Sprite).spriteFrame = res;
            })
        }

        Player.ins.initData();//初始化玩家属性值
        this.init();//初始化界面

        if (StartSceneGameMgr.ins.sceneGateLevel <= 7) {
            EnemyMgr.ins.createEnemy(2, enemyTypeEnum.putongjiangshi)//初次登场的怪物
        }
        else {
            EnemyMgr.ins.createEnemy(3, enemyTypeEnum.putongjiangshi)//初次登场的怪物
        }

        //初始化上阵角色
        let role = UserInfo.hasRoleDic.get(UserInfo.currGoBattleRoleId);
        resources.load(role.roleTp.rolePrePath, Prefab, (err, res) => {
            let pre = instantiate(res);
            pre.setParent(Player.ins.node);
            let comp = pre.getComponent(sp.Skeleton);
            comp.setAnimation(0, "Standby", true)

            comp.setCompleteListener((trackEntry) => {
                let name = trackEntry.animation ? trackEntry.animation.name : '';
                if (name === "Attack" || name === "ContinuousAttack") {
                    comp.setAnimation(0, "Standby", true)
                }
            });

        })

        //初始化宠物
        let goBattlePet = StartSceneGameMgr.ins.getGoBattlePet();

        if (goBattlePet) {
            this.currSelectPetSp.active = true;
            resources.load(`${goBattlePet.petTp.imgPath}/spriteFrame`, SpriteFrame, (err, res) => {
                this.currSelectPetSp.getComponent(Sprite).spriteFrame = res;
            })

            tween(this.currSelectPetSp)
                .tag(46)
                .to(0.4, { scale: v3(1, 1.1, 1), position: v3(0, 30, 0) })
                .to(0.4, { scale: v3(1, 1, 1), position: v3(0, 0, 0) })
                .union()
                .repeatForever()
                .start()
        }
        else {
            this.currSelectPetSp.active = false;
        }



    }

    /**
     * @description: 初始化界面
     * @return {*}
     */
    init() {

        this.LevelCountTable.getChildByName("Label").getComponent(Label).string = "关卡" + StartSceneGameMgr.ins.sceneGateLevel;

        for (let i = 0; i < this.endSkillPropRoot.children.length; i++) {
            this.endSkillPropRoot.children[i].getChildByName("value").getComponent(Label).string = UserInfo.hasEndSkillPropArr[i] + ""

            if (UserInfo.hasEndSkillPropArr[i] <= 0) {
                this.endSkillPropRoot.children[i].getChildByName("ad").active = true;
            }
            else {
                this.endSkillPropRoot.children[i].getChildByName("ad").active = false;
            }
        }

        //更新第几关解锁敌人的ui
        let lockEnemyTypeArr = [];

        UserInfo.enemyCongfiDic.getValueList().forEach((ele) => {

            if (ele.levelUplockNum <= StartSceneGameMgr.ins.sceneGateLevel) {
                this.unlockEnemyTypeArr.push(ele.enemyType);
            }
            else {
                lockEnemyTypeArr.push(ele.enemyType);
            }
        })

        if (lockEnemyTypeArr.length <= 0) {//敌人类型都解锁完了
            this.unLockEnemyTypeRoot.active = false;
        }
        else {
            this.unLockEnemyTypeRoot.active = true;
            lockEnemyTypeArr.sort((a, b) => {
                if (UserInfo.enemyCongfiDic.get(a).levelUplockNum < UserInfo.enemyCongfiDic.get(b).levelUplockNum) {
                    return -1
                }
                else {
                    return 1
                }
            });
            console.log(lockEnemyTypeArr, "lockEnemyTypeArr");
            let enemyCongfi = UserInfo.enemyCongfiDic.get(lockEnemyTypeArr[0]);
            this.unLockEnemyTypeRoot.getChildByName("Label").getComponent(Label).string = `第${enemyCongfi.levelUplockNum}关解锁`;

            resources.loadDir(enemyCongfi.spinesPath, sp.SkeletonData, (err, data) => {
                if (err) {
                    console.log(err);
                    return;
                } else {
                    let comp = this.unLockEnemyTypeRoot.getChildByName("sp").getComponent(sp.Skeleton);
                    comp.skeletonData = data[0];
                    comp.setAnimation(0, "idle", true);
                }
            })
        }

    }

    //失败页面点击重新开始
    onclickFailPanelReStartBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);
        this.failPanel.active = false;
        this.roundRoot.removeAllChildren();
        this.buttleRoot.removeAllChildren();
        this.enemyRoot.removeAllChildren();

        this.isGamePause = false
        this.isOpenZombieTide = false;
        EnemyMgr.ins.enemyNodeDic = new Dictionary();
        EnemyMgr.ins.enemyId = 0;
        Player.ins.playerSkillInfoDic = new Dictionary();
        Player.ins.playerSkillInfoDetailDic = new Dictionary();
        Player.ins.skillItemNodeDic = new Dictionary();
        this.skillCellContent.removeAllChildren();
        Player.ins.initData();
        this.attackEnemyList = [];

        if (StartSceneGameMgr.ins.sceneGateLevel <= 7) {
            EnemyMgr.ins.createEnemy(2, enemyTypeEnum.putongjiangshi)//初次登场的怪物
        }
        else {
            EnemyMgr.ins.createEnemy(3, enemyTypeEnum.putongjiangshi)//初次登场的怪物
        }
        this.updateSkillCount()
    }

    onclickReviveBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);

        //复活
        Adsdk.instance.showVideo(() => {
            this.isGamePause = false
            this.failPanel.active = false;

            // let pre = instantiate(this.AngelPre);
            // pre.setParent(find("Canvas"));
            // pre.setPosition(0, -362, 0);
            // setTimeout(() => {
            //     pre.destroy();
            // }, 2000)
            // Player.ins.createMoonSlash(30);

            // Player.ins.createSpinArrow(8)

            AudioMgr.ins.playOneShot("audio/tornado", 0.5);

            let pre = instantiate(this.tornadoEndSkillPropPre);
            pre.setParent(this.buttleRoot);
            pre.setPosition(0, 0, 0);
            pre.setScale(0.2, 0.2, 1)
            tween(pre)
                .to(1, { scale: v3(1.6, 1.6, 1) })
                .start()

            this.isTornadoIng = true;

            this.scheduleOnce(() => {
                pre.destroy();
                this.isTornadoIng = false;

                EnemyMgr.ins.enemyNodeDic.getValueList().forEach((ele) => {
                    ele.getComponent(Enemy).IsSufferTornadoIng = false;
                })
            }, 7)

            this.useWTornadoEndSkillProp();

            this.attackEnemyList = [];

        }, () => {

        })
    }

    //失败页面点击退出
    onclickFailPanelQuitBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);

        this.failPanel.active = false;
        director.loadScene("start")
    }

    onclickPanelConitnueBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);

        this.pausePanel.active = false;
        this.isGamePause = false;
    }

    onclickPausePanelQuitBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);

        this.pausePanel.active = false;
        director.loadScene("start")
    }

    onclickGamePauseBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);

        Adsdk.instance.showInterstitialAd()
        this.pausePanel.active = true;
        this.isGamePause = true
    }

    protected update(dt: number): void {

        if (!this.isGamePause) {

            this.tempCount += dt
            // this.giftTempUpdateTimeCount += dt
            if (this.IsPlayerDieTimeDowning == true) {
                this.TempUpdatePlayerDieTimeDown += dt;

            }

            if (this.tempCount >= randomNum(5, 7)) {//每5到7秒
                this.tempCount = 0;
                if (this.isTornadoIng == true) {//如果正在龙卷风，就不再刷怪,等龙卷风结束再开始继续刷怪
                    return;
                }

                if (!(Player.ins.Lv == 20)) {//如果刷怪到达击败数了就不再刷新怪
                    let extra_num = Math.floor(Player.ins.Lv * 0.4)
                    if (extra_num > 5) {
                        extra_num = 5
                    }
                    //创建敌人
                    if (StartSceneGameMgr.ins.sceneGateLevel == 1) {
                        if (!this.isOpenZombieTide) {
                            if (EnemyMgr.ins.enemyNodeDic.lenght <= 1 && Player.ins.Lv > 1) {
                                EnemyMgr.ins.createEnemy(3 + extra_num, 0);
                            } else {
                                EnemyMgr.ins.createEnemy(1 + extra_num, 0);
                            }
                        }
                        else {
                            if (EnemyMgr.ins.enemyNodeDic.lenght <= 1 && Player.ins.Lv > 1) {
                                EnemyMgr.ins.createEnemy(5 + extra_num, 0);
                            } else {
                                EnemyMgr.ins.createEnemy(2 + extra_num, 0);
                            }
                        }
                    }
                    else if (2 <= StartSceneGameMgr.ins.sceneGateLevel && StartSceneGameMgr.ins.sceneGateLevel < 4) {
                        extra_num = extra_num + 1

                        if (!this.isOpenZombieTide) {
                            if (EnemyMgr.ins.enemyNodeDic.lenght <= 1 && Player.ins.Lv > 1) {
                                EnemyMgr.ins.createEnemy(3 + extra_num, this.unlockEnemyTypeArr[randomNum(0, this.unlockEnemyTypeArr.length - 1)]);
                            } else {
                                EnemyMgr.ins.createEnemy(1 + extra_num, this.unlockEnemyTypeArr[randomNum(0, this.unlockEnemyTypeArr.length - 1)]);
                            }
                        }
                        else {
                            if (EnemyMgr.ins.enemyNodeDic.lenght <= 1 && Player.ins.Lv > 1) {
                                EnemyMgr.ins.createEnemy(5 + extra_num, this.unlockEnemyTypeArr[randomNum(0, this.unlockEnemyTypeArr.length - 1)]);
                            } else {
                                EnemyMgr.ins.createEnemy(2 + extra_num, this.unlockEnemyTypeArr[randomNum(0, this.unlockEnemyTypeArr.length - 1)]);
                            }
                        }
                    }
                    else if (4 <= StartSceneGameMgr.ins.sceneGateLevel && StartSceneGameMgr.ins.sceneGateLevel < 7) {
                        extra_num = extra_num + 2

                        if (!this.isOpenZombieTide) {
                            if (EnemyMgr.ins.enemyNodeDic.lenght <= 1 && Player.ins.Lv > 1) {
                                EnemyMgr.ins.createEnemy(3 + extra_num, this.unlockEnemyTypeArr[randomNum(0, this.unlockEnemyTypeArr.length - 1)]);
                            } else {
                                EnemyMgr.ins.createEnemy(1 + extra_num, this.unlockEnemyTypeArr[randomNum(0, this.unlockEnemyTypeArr.length - 1)]);
                            }
                        }
                        else {
                            if (EnemyMgr.ins.enemyNodeDic.lenght <= 1 && Player.ins.Lv > 1) {
                                EnemyMgr.ins.createEnemy(5 + extra_num, this.unlockEnemyTypeArr[randomNum(0, this.unlockEnemyTypeArr.length - 1)]);
                            } else {
                                EnemyMgr.ins.createEnemy(2 + extra_num, this.unlockEnemyTypeArr[randomNum(0, this.unlockEnemyTypeArr.length - 1)]);
                            }
                        }
                    }

                    else {
                        extra_num = extra_num + 3

                        if (!this.isOpenZombieTide) {
                            if (EnemyMgr.ins.enemyNodeDic.lenght <= 1 && Player.ins.Lv > 1) {
                                EnemyMgr.ins.createEnemy(3 + extra_num, this.unlockEnemyTypeArr[randomNum(0, this.unlockEnemyTypeArr.length - 1)]);
                            } else {
                                EnemyMgr.ins.createEnemy(1 + extra_num, this.unlockEnemyTypeArr[randomNum(0, this.unlockEnemyTypeArr.length - 1)]);
                            }
                        }
                        else {
                            if (EnemyMgr.ins.enemyNodeDic.lenght <= 1 && Player.ins.Lv > 1) {
                                EnemyMgr.ins.createEnemy(5 + extra_num, this.unlockEnemyTypeArr[randomNum(0, this.unlockEnemyTypeArr.length - 1)]);
                            } else {
                                EnemyMgr.ins.createEnemy(2 + extra_num, this.unlockEnemyTypeArr[randomNum(0, this.unlockEnemyTypeArr.length - 1)]);
                            }
                        }
                    }
                }
                else {
                    console.log("不再刷怪")
                    if (EnemyMgr.ins.enemyNodeDic.lenght <= 0) {//场上没怪，并且生成怪数到达本关要求，执行下一关
                        console.log("游戏胜利")
                        this.gameWin();
                    }
                }
            }

            // //礼物
            // if (!this.isGamePause) {
            //     if (this.giftTempUpdateTimeCount > randomNum(25,35)) {
            //         this.giftTempUpdateTimeCount = 0;
            //         this.createGift()

            //     }
            // }


            //玩家死亡倒计时

            if (this.attackEnemyList.length <= 0) {//取消玩家死亡倒计时
                this.IsPlayerDieTimeDowning = false
                this.TempUpdatePlayerDieTimeDown = 0;
            }

            if (this.IsPlayerDieTimeDowning == true) {
                if (this.TempUpdatePlayerDieTimeDown > this.playerDieTimeDownTotalMun) {
                    this.TempUpdatePlayerDieTimeDown = 0;
                    this.IsPlayerDieTimeDowning = false;
                    this.gameOver();
                }
            }

            //角色技能升级处理
            if (Player.ins.waitHandleUpSkillLevelNum > 0) {
                this.isGamePause = true;
                Player.ins.waitHandleUpSkillLevelNum -= 1;
                AudioMgr.ins.playOneShot("audio/LevelUp", 0.6);
                Player.ins.selectSkillPanel.active = true;
                Adsdk.instance.showInterstitialAd2()
                Player.ins.selectSkillPanel.getComponent(SelectSkillPanel).init();
            }


        }
    }

    /**
   * 绘制龙骨动画
   * @param skeletonName 
   */
    public createSkeleton(skeletonPath, skeletonCom: dragonBones.ArmatureDisplay) {

        resources.loadDir(skeletonPath, null, function (err, asset) {

            //检查资源加载
            if (err) {
                console.warn('预加载:', "失败， 原因:", err);
                return;
            }

            for (let k = 0; k < asset.length; ++k) {
                let res = asset[k];
                if (res instanceof dragonBones.DragonBonesAsset) {
                    skeletonCom.dragonAsset = res;
                } else if (res instanceof dragonBones.DragonBonesAtlasAsset) {
                    skeletonCom.dragonAtlasAsset = res;
                    console.log("skeletonCom.dragonAtlasAsset", skeletonCom.dragonAtlasAsset)
                }
            }
            skeletonCom.armatureName = "armatureName";
            //   skeletonCom.playAnimation("Sprite", 0);

            //   console.log(skeletonCom,"skeletonCom")
        });

    }

    /**
  * @description: 面向敌人移动
  * @return {*}
  */
    public trackTargetMove(targetPos, selfNode, speed, dt) {

        if (!targetPos) {
            return
        }

        let speedArr = trackTarget(targetPos.x, targetPos.y, selfNode.position.x, selfNode.position.y, speed * dt);

        this.tempPos = v2();
        selfNode.getPosition(this.tempPos);
        this.tempPos.x += speedArr[0]
        this.tempPos.y += speedArr[1]
        selfNode.setPosition(this.tempPos);

        selfNode.angle = speedArr[2] * (180 / Math.PI);


        //如果自己已经到达敌人附近，自己销毁
        if (getDistance(selfNode.position.x, selfNode.position.y, targetPos.x, targetPos.y) < 5) {
            // this.creatMinTip(targetPos, "未命中要改")
            console.log("销毁")
            selfNode.destroy()
        }

    }

    targetLineMove(tarPos, selfNode, speed) {
        if (tarPos == null) {
            selfNode.destroy();
        }
        //把touch世界坐标转换到节点gamePlay下面的坐标
        //  touch_end_pos = this.gamePlay.convertToNodeSpaceAR(touch_end_pos)
        //坐标差值
        var pos_cha = v2(tarPos.x - selfNode.position.x, tarPos.y - selfNode.position.y)
        //获取单位向量，我也不是很懂，通过勾股定理
        var xiebian = Math.sqrt(pos_cha.x * pos_cha.x + pos_cha.y * pos_cha.y)
        pos_cha.x = pos_cha.x / xiebian * speed
        pos_cha.y = pos_cha.y / xiebian * speed
        //给小球赋值发射方向  向量
        //  selfNode.setPosition(selfNode.getPosition()*pos_cha.x)
        selfNode.getComponent(RigidBody2D).linearVelocity = pos_cha;
    }

    creatMinTip(createPos, _label, isCriticalHit, colorFromHEX = null) {
        // let tipPre = instantiate(this.minTipPre);
        let tipPre = PoolMgr.ins.poolGet("minTip");
        tipPre.setParent(find("Canvas/bg/minTpRoot"));
        tipPre.setPosition(createPos.x, createPos.y);
        tipPre.getChildByName("Label").getComponent(Label).string = _label;


        if (isCriticalHit) {
            tipPre.getChildByName("criticalHitIcon").active = true;
            tipPre.getChildByName("Label").getComponent(Label).color = Color.RED;

        }
        else {
            tipPre.getChildByName("criticalHitIcon").active = false;
            if (colorFromHEX) {
                tipPre.getChildByName("Label").getComponent(Label).color = new Color().fromHEX(colorFromHEX);
            }
            else {
                tipPre.getChildByName("Label").getComponent(Label).color = Color.WHITE;
            }
        }
        // setTimeout(() => {
        //     tipPre.destroy();
        // }, 1000)
        tween(tipPre)
            .by(0.3, { position: v3(0, 10) })
            .call(() => {
                Tween.stopAllByTarget(tipPre);
                PoolMgr.ins.poolPut("minTip",tipPre)
            })
            .start();

    }

    test() {
        this.summonAngelHelp();
    }

    //下一关
    nextLevel() {
        this.roundRoot.removeAllChildren();
        this.buttleRoot.removeAllChildren();
        this.enemyRoot.removeAllChildren();

        this.createWidowTip("恭喜过关，下一关开始")
        this.isOpenZombieTide = false;
        StartSceneGameMgr.ins.sceneGateLevel += 1;
        EnemyMgr.ins.enemyId = 0;
        Player.ins.playerSkillInfoDic = new Dictionary();
        Player.ins.playerSkillInfoDetailDic = new Dictionary();
        Player.ins.skillItemNodeDic = new Dictionary();
        EnemyMgr.ins.enemyNodeDic = new Dictionary();
        this.skillCellContent.removeAllChildren();
        Player.ins.initData();

        gameMgr.ins.init();//界面初始化

        //保存数据

        //局内用户数据
        StartSceneGameMgr.ins.saveGameDate();

    }

    createWidowTip(str) {
        let pre = instantiate(this.widowTipPre);
        pre.setParent(this.windowPopTipRoot);
        pre.setPosition(0, -50);
        pre.getChildByName("Label").getComponent(Label).string = str;
        tween(pre)
            .to(0.5, { position: v3(0, 0, 0) })
            .delay(2)
            .call(() => {
                pre.destroy();
            })
            .start()
    }

    createGift() {
        let giftPre = instantiate(this.giftPre);
        giftPre.setParent(find("Canvas"));
        giftPre.setPosition(-492, -145)
        giftPre.on(Node.EventType.TOUCH_START, (() => {
            giftPre.destroy();
            this.giftonClick();
        }), this)
        tween(giftPre)
            .to(2, { position: v3(-222, -21, 0) })
            .to(2, { position: v3(-59, -140, 0) })
            .to(2, { position: v3(-59, -140, 0) })
            .to(2, { position: v3(24, -37, 0) })
            .to(2, { position: v3(178, -131, 0) })
            .to(2, { position: v3(440, -200, 0) })
            .call(() => {
                giftPre.destroy();
            })
            .start();

    }

    giftonClick() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);

        this.giftPanel.active = true;
    }

    onclickGiftPanelComfirm() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);

        Adsdk.instance.showVideo(() => {
            this.giftPanel.active = false;
            this.summonAngelHelp();
        }, () => {

        })
    }

    onclickGiftPanelQuit() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);

        this.giftPanel.active = false;
    }

    openWinPanel() {
        let isHasRewardDouble = false;//是否奖励翻倍
        let goBattlePet = StartSceneGameMgr.ins.getGoBattlePet();
        if (goBattlePet && goBattlePet.petTp.petType == 3) {
            isHasRewardDouble = true
        }

        Adsdk.instance.showInterstitialAd()
        this.isGamePause = true;
        this.winPanel.active = true;
        let content = this.winPanel.getChildByName("rewardsRoot").getChildByName("ScrollView").getChildByName("view").getChildByName("content");
        this.winPanel.getChildByName("timeLabel").getComponent(Label).string = TimeCountTable.ins.formatTime(TimeCountTable.ins.elapsedTime);

        //奖励
        //必得晶体
        content.removeAllChildren();
        let rewardCrystalNum = randomNum(20, 50);
        rewardCrystalNum += StartSceneGameMgr.ins.sceneGateLevel * 3;
        if (isHasRewardDouble) {
            rewardCrystalNum += rewardCrystalNum;//持有宠物七星瓢虫奖励翻倍
        }

        let pre = instantiate(this.rewardCellPre);
        pre.setParent(content);
        let rewardCongfi = UserInfo.rewardCongfiDic.get(rewardEnum.crystal);
        rewardCongfi.count = rewardCrystalNum;
        pre.getComponent(RewardCellItem).init(rewardCongfi)
        UserInfo.crystalMun += rewardCrystalNum;
        //大招卡
        let rand = randomNum(0, 2);//百分之65几率获得大招卡
        if (rand != 0) {
            let endSkillPropNum = randomNum(2, 5);
            endSkillPropNum += Math.floor(StartSceneGameMgr.ins.sceneGateLevel * 0.4);

            if (isHasRewardDouble) {
                endSkillPropNum += endSkillPropNum;//持有宠物七星瓢虫奖励翻倍
            }

            let endSkillPropType = randomNum(0, 2);

            let pre = instantiate(this.rewardCellPre);
            pre.setParent(content);
            let rewardCongfi = UserInfo.rewardCongfiDic.get(endSkillPropType + 3);
            rewardCongfi.count = endSkillPropNum;
            pre.getComponent(RewardCellItem).init(rewardCongfi)
            UserInfo.hasEndSkillPropArr[endSkillPropType] += endSkillPropNum;
        }
        //必得金币
        let getCoinNum = randomNum(20, 50);
        getCoinNum += StartSceneGameMgr.ins.sceneGateLevel * 3;

        if (isHasRewardDouble) {
            getCoinNum += getCoinNum;//持有宠物七星瓢虫奖励翻倍
        }

        let pre3 = instantiate(this.rewardCellPre);
        pre3.setParent(content);
        let rewardCongfi3 = UserInfo.rewardCongfiDic.get(rewardEnum.coin);
        rewardCongfi3.count = getCoinNum;
        pre3.getComponent(RewardCellItem).init(rewardCongfi3)
        UserInfo.coinMun += getCoinNum;


        StartSceneGameMgr.ins.saveGameDate();

    }

    onclickWinPanelQuitBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);

        director.loadScene("start")
    }
    onclickWinPanelNextLevelBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);

        this.nextLevel();
        this.isGamePause = false;
        this.winPanel.active = false;
    }

    //点击道具风
    onclickWindEndSkillPropBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);

        if (UserInfo.hasEndSkillPropArr[0] > 0) {
            UserInfo.hasEndSkillPropArr[0] -= 1;
            this.windEndSkill()
        }
        else {
            Adsdk.instance.showVideo(() => {
                this.windEndSkill()
            }, () => {

            })
        }
    }

    //道具风
    windEndSkill(){
        let btnNode = this.endSkillPropRoot.getChildByName("windEndSkillPropBtn");
        btnNode.getComponent(Sprite).color = new Color().fromHEX("#353535");
        btnNode.getComponent(Button).enabled = false;

        this.scheduleOnce(() => {
            btnNode.getComponent(Sprite).color = new Color().fromHEX("#FFFFFF");
            btnNode.getComponent(Button).enabled = true;
        }, 3.3)

        AudioMgr.ins.playOneShot("audio/tornado", 0.5);
        this.createWidowTip("风之召唤")
        this.useWindEndSkillProp();
        StartSceneGameMgr.ins.saveGameDate();
        btnNode.getChildByName("value").getComponent(Label).string = UserInfo.hasEndSkillPropArr[0] + ""
        this.updateSkillCount()
    }

    //点击道具狂暴
    onclickRabidEndSkillPropBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);

        if (UserInfo.hasEndSkillPropArr[1] > 0) {
            UserInfo.hasEndSkillPropArr[1] -= 1;
            this.rabidEndSkill()
        }
        else {
            Adsdk.instance.showVideo(() => {
                this.rabidEndSkill()
            }, () => {

            })

        }
    }

    //道具狂暴
    rabidEndSkill() {

        let btnNode = this.endSkillPropRoot.getChildByName("rabidEndSkillPropBtn");
        btnNode.getComponent(Sprite).color = new Color().fromHEX("#353535");
        btnNode.getComponent(Button).enabled = false;

        let pre = instantiate(this.rabidEndSkillPropPre);
        pre.setParent(this.buttleRoot);
        let playerWorldPos = Player.ins.node.getWorldPosition();
        let resPos = this.buttleRoot.getComponent(UITransform).convertToNodeSpaceAR(playerWorldPos);
        pre.setPosition(resPos.x, resPos.y + 20);
        AudioMgr.ins.playOneShot("audio/rabid", 0.5);
        this.createWidowTip("狂暴之怒")

        this.scheduleOnce(() => {
            Player.ins.isOpenRabid = false;
            Player.ins.arrowFrequency += 0.3;

            btnNode.getComponent(Sprite).color = new Color().fromHEX("#FFFFFF");
            btnNode.getComponent(Button).enabled = true;
            pre.destroy();

        }, 10)

        Player.ins.isOpenRabid = true;
        Player.ins.arrowFrequency -= 0.3;
        if (Player.ins.arrowFrequency < 0.2) {
            Player.ins.arrowFrequency = 0.2
        }
        StartSceneGameMgr.ins.saveGameDate();
        btnNode.getChildByName("value").getComponent(Label).string = UserInfo.hasEndSkillPropArr[1] + ""
        this.updateSkillCount()
    }


    //点击道具龙卷风
    onclickTornadoEndSkillPropBtn() {
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);
        if (UserInfo.hasEndSkillPropArr[2] > 0) {
            UserInfo.hasEndSkillPropArr[2] -= 1;
            this.tornadoEndSkill()
        }
        else {
            Adsdk.instance.showVideo(() => {
                this.tornadoEndSkill()
            }, () => {

            })

        }
    }

    tornadoEndSkill(){

        let btnNode = this.endSkillPropRoot.getChildByName("tornadoEndSkillPropBtn");
        btnNode.getComponent(Sprite).color = new Color().fromHEX("#353535");
        btnNode.getComponent(Button).enabled = false;

        this.createWidowTip("召唤混沌龙卷")
        AudioMgr.ins.playOneShot("audio/tornado", 0.5);

        let pre = instantiate(this.tornadoEndSkillPropPre);
        pre.setParent(this.buttleRoot);
        pre.setPosition(0, 0, 0);
        pre.setScale(0.2, 0.2, 1)
        tween(pre)
            .to(1, { scale: v3(1.6, 1.6, 1) })
            .start()

        this.isTornadoIng = true;

        this.scheduleOnce(() => {
            btnNode.getComponent(Sprite).color = new Color().fromHEX("#FFFFFF");
            btnNode.getComponent(Button).enabled = true;
            pre.destroy();
            this.isTornadoIng = false;

            EnemyMgr.ins.enemyNodeDic.getValueList().forEach((ele) => {
                ele.getComponent(Enemy).IsSufferTornadoIng = false;
            })
        }, 7)

        this.useWTornadoEndSkillProp();
        StartSceneGameMgr.ins.saveGameDate();
        btnNode.getChildByName("value").getComponent(Label).string = UserInfo.hasEndSkillPropArr[2] + ""
        this.updateSkillCount()
    }

    updateSkillCount(){

        for (let i = 0; i < this.endSkillPropRoot.children.length; i++) {
            this.endSkillPropRoot.children[i].getChildByName("value").getComponent(Label).string = UserInfo.hasEndSkillPropArr[i] + ""

            if (UserInfo.hasEndSkillPropArr[i] <= 0) {
                this.endSkillPropRoot.children[i].getChildByName("ad").active = true;
            }
            else {
                this.endSkillPropRoot.children[i].getChildByName("ad").active = false;
            }
        }

        if (UserInfo.hasEndSkillPropArr[0] <= 0) {
            this.endSkillPropRoot.children[0].getChildByName("ad").active = true;
        }
        else {
            this.endSkillPropRoot.children[0].getChildByName("ad").active = false;
        }

        if (UserInfo.hasEndSkillPropArr[1] <= 0) {
            this.endSkillPropRoot.children[1].getChildByName("ad").active = true;
        }
        else {
            this.endSkillPropRoot.children[1].getChildByName("ad").active = false;
        }

        if (UserInfo.hasEndSkillPropArr[2] <= 0) {
            this.endSkillPropRoot.children[2].getChildByName("ad").active = true;
        }
        else {
            this.endSkillPropRoot.children[2].getChildByName("ad").active = false;
        }

    }


    useWindEndSkillProp() {
        let pre = instantiate(this.windEndSkillPropPre);
        pre.setParent(this.buttleRoot);
        pre.setPosition(0, -(StartSceneGameMgr.ins._windowHeight / 2 + 300));

        EnemyMgr.ins.enemyNodeDic.getValueList().forEach((ele) => {
            ele.getComponent(Enemy).isNotMove = true;

            let moveByWind = 700 / ele.getComponent(Enemy).enemyTp.mass;

            if (ele.position.y > 0) {
                if (ele.position.y + 700 / ele.getComponent(Enemy).enemyTp.mass > StartSceneGameMgr.ins.enemyGenerateY) {
                    moveByWind = StartSceneGameMgr.ins.enemyGenerateY - ele.position.y
                }
            }
            else {
                console.log("敌人预制体位置y值是负的,没出先这种情况先不处理")
            }

            tween(ele)
                .by(3, { position: v3(0, moveByWind, 0) })
                .call(() => {
                    if (ele.isValid) {
                        ele.getComponent(Enemy).isNotMove = false;
                    }
                    pre.destroy();
                })
                .start()
        })
    }

    useWTornadoEndSkillProp() {

        EnemyMgr.ins.enemyNodeDic.getValueList().forEach((ele) => {
            ele.getComponent(Enemy).IsSufferTornadoIng = true;
        })
    }

    gameWin() {
        AudioMgr.ins.playOneShot("audio/win", 0.6);
        this.openWinPanel();
        if (StartSceneGameMgr.ins.sceneGateLevel == UserInfo.level) {
            UserInfo.level += 1;
            StartSceneGameMgr.ins.sceneGateLevel += 1;
        }
        UserInfo.todayWinGateNum += 1;
        StartSceneGameMgr.ins.saveGameDate();
    }

    //召唤天使帮助
    summonAngelHelp() {
        let pre = instantiate(this.AngelPre);
        pre.setParent(find("Canvas"));
        pre.setPosition(0, -362, 0);
        setTimeout(() => {
            pre.destroy();
        }, 2000)
        Player.ins.createMoonSlash(15);

    }

    //游戏失败
    gameOver() {
        AudioMgr.ins.playOneShot("audio/fail", 0.6);
        Adsdk.instance.showInterstitialAd()
        console.log("玩家死亡游戏结束")
        gameMgr.ins.failPanel.active = true;
        gameMgr.ins.isGamePause = true;
        this.playerDieTimeCountDownNode.active = false;
        let content = this.failPanel.getChildByName("rewardsRoot").getChildByName("ScrollView").getChildByName("view").getChildByName("content");
        this.failPanel.getChildByName("timeLabel").getComponent(Label).string = TimeCountTable.ins.formatTime(TimeCountTable.ins.elapsedTime);

        //奖励
        content.removeAllChildren();
        let rewardCrystalNum;
        let getCoinNum;
        let endSkillPropNum;

        if (TimeCountTable.ins.elapsedTime <= 60) {//1分钟
            rewardCrystalNum = randomNum(3, 6);
            getCoinNum = randomNum(3, 6);
            endSkillPropNum = 1;
        }
        else if (TimeCountTable.ins.elapsedTime > 60 && TimeCountTable.ins.elapsedTime <= 120) {//2分钟
            rewardCrystalNum = randomNum(6, 12);
            getCoinNum = randomNum(6, 12);
            endSkillPropNum = 1;
        }
        else if (TimeCountTable.ins.elapsedTime > 120 && TimeCountTable.ins.elapsedTime <= 360) {//3分钟
            rewardCrystalNum = randomNum(8, 16);
            getCoinNum = randomNum(8, 16);
            endSkillPropNum = randomNum(2, 3);
        }
        else {
            rewardCrystalNum = randomNum(15, 26);
            getCoinNum = randomNum(15, 26);
            endSkillPropNum = randomNum(2, 3);
        }

        rewardCrystalNum += StartSceneGameMgr.ins.sceneGateLevel;
        getCoinNum += StartSceneGameMgr.ins.sceneGateLevel;
        endSkillPropNum += Math.floor(StartSceneGameMgr.ins.sceneGateLevel * 0.2);

        //必得晶体
        let pre = instantiate(this.rewardCellPre);
        pre.setParent(content);
        let rewardCongfi = UserInfo.rewardCongfiDic.get(rewardEnum.crystal);
        rewardCongfi.count = rewardCrystalNum;
        pre.getComponent(RewardCellItem).init(rewardCongfi)
        UserInfo.crystalMun += rewardCrystalNum;
        //大招卡
        let rand = randomNum(0, 2);//百分之65几率获得大招卡
        if (rand != 0) {
            let endSkillPropType = randomNum(0, 2);

            let pre = instantiate(this.rewardCellPre);
            pre.setParent(content);
            let rewardCongfi = UserInfo.rewardCongfiDic.get(endSkillPropType + 3);
            rewardCongfi.count = endSkillPropNum;
            pre.getComponent(RewardCellItem).init(rewardCongfi)
            UserInfo.hasEndSkillPropArr[endSkillPropType] += endSkillPropNum;
        }
        //必得金币
        let pre3 = instantiate(this.rewardCellPre);
        pre3.setParent(content);
        let rewardCongfi3 = UserInfo.rewardCongfiDic.get(rewardEnum.coin);
        rewardCongfi3.count = getCoinNum;
        pre3.getComponent(RewardCellItem).init(rewardCongfi3)
        UserInfo.coinMun += getCoinNum;
        UserInfo.coinMun += getCoinNum;

        StartSceneGameMgr.ins.saveGameDate();
    }

    onclickAudioBgmBtn() {
        if (AudioMgr.ins.isAudioBgm) {
            AudioMgr.ins.isAudioBgm = false;
            AudioMgr.ins.stop();
            resources.load("UIImg/audioClose/spriteFrame", SpriteFrame, (err, res) => {
                this.pausePanel.getChildByName("audioBgmToggleImg").getComponent(Sprite).spriteFrame = res;
            })
        }
        else {
            AudioMgr.ins.isAudioBgm = true;
            AudioMgr.ins.play("audio/bgm1");
            resources.load("UIImg/audioOpen/spriteFrame", SpriteFrame, (err, res) => {
                this.pausePanel.getChildByName("audioBgmToggleImg").getComponent(Sprite).spriteFrame = res;
            })
        }
    }

    onclickAudioEffectBtn() {
        if (AudioMgr.ins.isAudioEffect) {
            AudioMgr.ins.isAudioEffect = false;
            resources.load("UIImg/audioClose/spriteFrame", SpriteFrame, (err, res) => {
                this.pausePanel.getChildByName("audioEffectToggleImg").getComponent(Sprite).spriteFrame = res;
            })
        }
        else {
            AudioMgr.ins.isAudioEffect = true;
            resources.load("UIImg/audioOpen/spriteFrame", SpriteFrame, (err, res) => {
                this.pausePanel.getChildByName("audioEffectToggleImg").getComponent(Sprite).spriteFrame = res;
            })
        }
    }
}


